CREATE FUNCTION func_getSoLuongTonKho
(
	@STTHangHoa int
)
RETURNS nvarchar(300)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @SoLuong float,
			@SoLuongTonKho nvarchar(300),
			@curDanhSachDonViTinh Cursor,
			@TenDonViTinh nvarchar(50),
			@GiaTriQuiDoi float,
			@SoLuongQuiDoi int

	-- Add the T-SQL statements to compute the return value here
	set @SoLuongTonKho = ''
	SELECT @Soluong = SoLuongTonKho from HangHoa where STT = @STTHangHoa
	Set @curDanhSachDonViTinh = cursor for select TenDonViTinh, GiaTriQuiDoi from DonViTinh where STTHangHoa = @STTHangHoa order by GiaTriQuiDoi desc
	
	OPEN @curDanhSachDonViTinh
	FETCH NEXT FROM @curDanhSachDonViTinh INTO @TenDonViTinh, @GiaTriQuiDoi
	WHILE @@FETCH_STATUS = 0
	BEGIN
		set @SoLuongQuiDoi = @Soluong / @GiaTriQuiDoi
		If @SoLuongQuiDoi > 0
		Begin
			set @SoLuongTonKho = @SoLuongTonKho + CONVERT(varchar(11),@SoLuongQuiDoi) + ' ' + @TenDonViTinh + ' '
			set @SoLuong = @SoLuong - (@SoLuongQuiDoi * @GiaTriQuiDoi)
		End
		FETCH NEXT FROM @curDanhSachDonViTinh INTO @TenDonViTinh, @GiaTriQuiDoi
	END
	
	Return @SoLuongTonKho
END